package com.fengjue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengjue.common.RespBean;
import com.fengjue.common.utils.JedisUtil;
import com.fengjue.config.security.JwtTokenUtil;
import com.fengjue.mapper.AdminMapper;
import com.fengjue.mapper.AdminRoleMapper;
import com.fengjue.mapper.RoleMapper;
import com.fengjue.pojo.Admin;
import com.fengjue.pojo.AdminRole;
import com.fengjue.pojo.Role;
import com.fengjue.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fengjue
 * @since 2021-03-10
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登录之后返回token
     *
     * @param username 用户的姓名
     * @param password 用户的密码
     * @param code     用户的验证码
     * @param request  请求
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {

        // 通过名字去查 角色
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码错误，请重新输入");
        }
        // 用户密码验证
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确11111");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员");
        }


        // 更新security登录用户对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(
                        userDetails,
                        null,
                        userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHeader", tokenHead);

        // 返回token
        return RespBean.success("登录成功", map);
    }

    /**
     * 根据用户名获取用户
     *
     * @param name
     * @return
     */
    @Override
    public Admin getAdminByUserName(String name) {


        return adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("username", name)
                .eq("enabled", true)
        );
    }

    /**
     * 根据用户id查询角色列表
     *
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        JedisUtil.Strings s = jedisUtil.new Strings();
        GenericJackson2JsonRedisSerializer gz = new GenericJackson2JsonRedisSerializer();

        String getRoles = new String("getRoles");
        byte[] serialize1 = gz.serialize(getRoles);
        byte[] bytes = s.get(serialize1);

        if (bytes == null) {
            List<Role> roles = roleMapper.getRoles(adminId);
            byte[] serialize = gz.serialize(roles);
            s.set(serialize1, serialize);
        }
//        resource.set
        List<Role> deserialize = (List<Role>) gz.deserialize(bytes);
        System.gc();
//        return roleMapper.getRoles(adminId);
        return deserialize;
    }

    /**
     * 获取所有操作员
     *
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        Admin principal = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer id = principal.getId();
        List<Admin> admin = adminMapper.getAllAdmins(id, keywords);
        return admin;
    }

    /**
     * 更新操作员的角色
     *
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        // 更新 =  先删除，再插入
        int adminId1 = adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));
        Integer result = adminRoleMapper.updateAdminRole(adminId, rids);
        if (rids.length == result) {
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @Override
    public RespBean updateByIdAdminPassword(String oldpass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldpass, admin.getPassword())) {
            admin.setPassword(encoder.encode(pass));
            int update = adminMapper.updateById(admin);
            if (1 == update) {
                return RespBean.success("更新成功！");
            }
        }
        return RespBean.error("更新失败！");
    }

    /**
     * 更新头像
     *
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int update = adminMapper.updateById(admin);
        if (1 == update) {
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(
                            admin, null, authentication.getAuthorities()
                    )
            );
            return RespBean.success("更新成功", url);
        }

        return RespBean.error("更新失败");
    }

}
